#include "GeomPlane.h"

//// Get matrix that converts a point from plane space to world space (2D -> 3D)
//// v3D = mat * (v2D , 1)
//Mat3d GeomPlane::getLocalToWorldMatrix(){
//	Mat3d mat;
//
//	mat[0][0]=mBasisU[0];
//	mat[1][0]=mBasisU[1];
//	mat[2][0]=mBasisU[2];
//
//	mat[0][1]=mBasisV[0];
//	mat[1][1]=mBasisV[1];
//	mat[2][1]=mBasisV[2];
//
//	mat[0][2]=mNormal[0] * (-mConstant);
//	mat[1][2]=mNormal[1] * (-mConstant);
//	mat[2][2]=mNormal[2] * (-mConstant);
//
//	return mat;
//}

// Transform a plane by the inverse of Matrix
GeomObject* GeomPlane::getObjApplyInvTransform(const Mat4d &_mat)
{ 
	Vec3d t(_mat[0][3], _mat[1][3], _mat[2][3]);
	double constant = mConstant + dot(mNormal, t);

	// Multiply normal by transpose of inverse -> directions are preserved
	Vec4d _norm = trans(_mat)*Vec4d(mNormal, 0);
	Vec3d normal(_norm[0], _norm[1], _norm[2]);

	double leng = len(normal);
	constant /= leng;
	normal /= leng;

	return new GeomPlane(normal, constant);
}

void GeomPlane::draw(Vec4d _col, bool _default){
	Vec3d origin = -mConstant*mNormal;
	Vec3d a(mNormal[2], 0, -mNormal[0]);
	double theta = acos(mNormal[1]);
	bool flip = true;
	bool flipx = false;
	bool flipy = false;
	glDisable(GL_LIGHTING);
	glPushMatrix();
	glTranslatef(origin[0], origin[1], origin[2]);
	glRotatef(theta*180/M_PI, a[0],a[1],a[2]);
	int blockx = ceil(mDim[0]/2);
	int blocky = ceil(mDim[1]/2);
	for(int i = -blockx; i < blockx; i++){
		if(i==-blockx) {
			flip=!flipx;
			flipx=flip;
		}
		double x1=i, x2=i+1;
		if(abs(x1)>mDim[0]/2) x1=moremath::sgn(x1)*mDim[0]/2;
		if(abs(x2)>mDim[0]/2) x2=moremath::sgn(x2)*mDim[0]/2;
		for(int j = -blocky; j < blocky; j++){
			if(j==-blocky){
				flip=!flipy;
				flipy=flip;
			}
			if(flip == true){
				//glColor4d(255/256.0, 200/256.0, 200/256.0, 0.5);
				glColor4d(mColor[0], mColor[1], mColor[2], mColor[3]);
				flip = false;
			}else{
				//glColor4d(200/256.0, 150/256.0, 150/256.0, 0.5);
				glColor4d(mColor[0]-0.2, mColor[1]-0.2, mColor[2]-0.2, mColor[3]);
				flip = true;
			}
			glBegin(GL_QUADS);
			glNormal3d(0,1,0);
			double y1=j, y2=j+1;
			if(abs(y1)>mDim[1]/2) y1=moremath::sgn(y1)*mDim[1]/2;
			if(abs(y2)>mDim[1]/2) y2=moremath::sgn(y2)*mDim[1]/2;
			glVertex3d(x1, 0, y1);
			glVertex3d(x1, 0, y2);
			glVertex3d(x2, 0, y2);
			glVertex3d(x2, 0, y1);
			glEnd();
		}
	}
	glPopMatrix();
	glEnable(GL_LIGHTING);
}
